package com.yuecai.modules.yc_order.service.impl;

import com.yuecai.modules.security.JwtUserDto;
import com.yuecai.modules.yc_coupon.service.YcCouponService;
import com.yuecai.modules.yc_goods.vo.YcGoodsOrderVo;
import com.yuecai.modules.yc_goods_sku.domain.YcGoodsSku;
import com.yuecai.modules.yc_goods_sku.repository.YcGoodsSkuRepository;
import com.yuecai.modules.yc_order.domain.YcOrder;
import com.yuecai.modules.yc_order.repository.YcOrderRepository;
import com.yuecai.modules.yc_order.service.OrderService;
import com.yuecai.modules.yc_order.service.dto.OrderDto;
import com.yuecai.modules.yc_order.service.dto.SubmitOrderDto;
import com.yuecai.modules.yc_order.service.utils.CoupontUtils;
import com.yuecai.modules.yc_order.service.utils.MakeOrderNum;
import com.yuecai.modules.yc_order.service.utils.OrderUtils;
import com.yuecai.modules.yc_order.service.vo.OrderVo;
import com.yuecai.modules.yc_order_goods.domain.YcOrderGoods;
import com.yuecai.modules.yc_order_goods.repository.YcOrderGoodsRepository;
import com.yuecai.modules.yc_receiver_info.domain.YcReceiverInfo;
import com.yuecai.modules.yc_receiver_info.repository.YcReceiverInfoRepository;
import com.yuecai.modules.yc_user.service.dto.YcUserDto;
import com.yuecai.modules.yc_user_coupon.domain.YcUserCoupon;
import com.yuecai.modules.yc_user_coupon.repository.YcUserCouponRepository;
import com.yuecai.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Service
public class BuyNowService implements OrderService {

    @Autowired
    private YcGoodsSkuRepository ycGoodsSkuRepository;
    @Autowired
    private YcReceiverInfoRepository receiverInfoRepository;
    @Autowired
    private OrderUtils orderUtils;
    @Autowired
    private YcOrderGoodsRepository ycOrderGoodsRepository;
    @Autowired
    private YcOrderRepository ycOrderRepository;

    @Autowired
    private YcCouponService ycCouponService;

    @Autowired
    private CoupontUtils coupontUtils;

    @Autowired
    private YcUserCouponRepository ycUserCouponRepository;

    @Override
    public ResponseEntity<Object> writeOrder(OrderDto dto) throws Exception {
        JwtUserDto currentUser = (JwtUserDto) SecurityUtils.getCurrentUser();
        Long userId = Long.valueOf(SecurityUtils.getCurrentUsername());
        YcUserDto user = currentUser.getUser();
        Integer level = user.getLevel();

        Integer count = dto.getCount();
        Long skuId = dto.getSkuId();
        Optional<YcGoodsSku> oSku = ycGoodsSkuRepository.findById(skuId);

        ArrayList<YcGoodsOrderVo> vos = new ArrayList<>();

        YcGoodsOrderVo ycGoodsVo = orderUtils.getPriviceByLevel(level,oSku,count);
        vos.add(ycGoodsVo);
        BigDecimal totalPrice = new BigDecimal(count).multiply(ycGoodsVo.getSellPrice());

        OrderVo vo = new OrderVo();
        YcReceiverInfo receiverInfo = receiverInfoRepository.findByUserIdAndDefaultSignTrue(userId);

        ResponseEntity responseEntity = orderUtils.checkTotalPrice(totalPrice);
        if (responseEntity!=null){
            return responseEntity;
        }
        List<YcUserCoupon> coupont = coupontUtils.findCoupont(vos, userId, totalPrice);

        vo.setReceiverInfo(receiverInfo);
        vo.setTotalPrice(totalPrice);
        vo.setYcGoodsOrderVos(vos);
        vo.setCoupont(coupont);
        return ResponseEntity.ok(vo);
    }

    @Override
    public ResponseEntity showPrice(SubmitOrderDto dto) throws Exception {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity submitOrder(SubmitOrderDto dto) throws Exception {
        Long receiveId = dto.getReceiveId();
        Long skuId = dto.getSkuId();
        Integer count = dto.getCount();
        Long userId = SecurityUtils.getCurrentUserId();
        Optional<YcReceiverInfo> byId = receiverInfoRepository.findById(receiveId);
        if (!byId.isPresent()){
            throw new Exception("收货地址不存在！");
        }
        JwtUserDto currentUser = (JwtUserDto) SecurityUtils.getCurrentUser();
        YcUserDto user = currentUser.getUser();
        Integer level = user.getLevel();

        Optional<YcGoodsSku> oSku = ycGoodsSkuRepository.findById(skuId);

        YcGoodsOrderVo ycGoodsVo = orderUtils.getPriviceByLevel(level,oSku,count);
        BigDecimal multiply = ycGoodsVo.getSellPrice().multiply(new BigDecimal(count));
        YcOrder ycOrder = new YcOrder();
        String s = MakeOrderNum.makeOrderNum();
        YcOrderGoods orderGood = orderUtils.getOrderGood(ycGoodsVo,s,count);
        //TODO 计算优惠
        BigDecimal payPrice = multiply;

        ycOrder.setOrderSn(s);
        ycOrder.setOrderStatus(0);
        ycOrder.setPayPrice(multiply);
        ycOrder.setReceiverId(receiveId);
        ycOrder.setTotalPrice(multiply);
        ycOrder.setUserId(userId);
        ycOrder.setRemarks(dto.getRemarks());
        ycOrder.setSupplierId(ycGoodsVo.getSupplierId());


        Long couponId = dto.getCouponId();
        YcUserCoupon coupon = null;
        List<YcGoodsOrderVo> vos = new ArrayList<>();
        vos.add(ycGoodsVo);
        coupon = coupontUtils.isUse(dto.getCouponId(),vos,ycGoodsVo.getSpecialOffer()==1 ? BigDecimal.valueOf(0) : payPrice);
        if (coupon!=null){
            Integer discountType = coupon.getDiscountType();
            BigDecimal discount = coupon.getDiscount();
            BigDecimal discountsPrice = BigDecimal.valueOf(0);
            if (discountType == 0){
                discountsPrice = discount;
                payPrice = payPrice.subtract(discount);
            }else if (discountType == 1){
                BigDecimal divide = payPrice.multiply(discount).divide(BigDecimal.valueOf(10), 2);
                discountsPrice = payPrice.subtract(divide);
                payPrice = divide;
            }
            ycOrder.setDiscountsPrice(discountsPrice);
            ycOrder.setCouponId(couponId);
        }
        ResponseEntity responseEntity = orderUtils.checkTotalPrice(payPrice);
        if (responseEntity!=null){
            return responseEntity;
        }
        if (coupon!=null){
            coupon.setIsUse(1);
            ycUserCouponRepository.save(coupon);
        }

        ycOrderRepository.save(ycOrder);
        ycOrderGoodsRepository.save(orderGood);
        try {
            BigDecimal specialOffer = ycGoodsVo.getSpecialOffer() == 1 ? BigDecimal.valueOf(0) : payPrice;
            ycCouponService.giveYcCoupon(payPrice,specialOffer,userId);
        }catch (Exception e){
            System.out.println("领取优惠券失败！");
            e.printStackTrace();
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("orderSn",s);
        map.put("payPrice",payPrice);
        return ResponseEntity.ok(map);
    }

}
